﻿using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.ReadApi.Command;
using U.B.ReadApi.Dto;
using U.B.Repistory;

namespace U.B.ReadApi.CommandHander
{
    public class MenuGetAllCommandHander : IRequestHandler<MenuGetAllCommand, Apipage<MenuDto>>
    {
        private readonly IRepistory<Menu> _menurepistory;

        public MenuGetAllCommandHander(IRepistory<Menu> menurepistory)
        {
            _menurepistory = menurepistory;
        }
        public Task<Apipage<MenuDto>> Handle(MenuGetAllCommand request, CancellationToken cancellationToken)
        {
            Apipage<MenuDto> apiresult = new Apipage<MenuDto>();
            var menus = _menurepistory.GetAll();
            apiresult.code = Renum.显示成功;
            apiresult.Message = Renum.显示成功.ToString();
            var list1 = _menurepistory.GetAll();
            Menu menu = new Menu
            {
                MenuId = 0,
                MenuName = "",
                PId = -1,
                MenusUrl = "",
                CreationDate = DateTime.Now,
                Creator = "",
                Updatedate = DateTime.Now,
                Updateor = ""
            };
            var m2 = list1.ToList();
            var list2 = from a in m2
                        join b in m2
                       on a.MenuId equals b.PId
                       where a.IsDeleted == false
                       select new MenuDto
                       {
                           MenuId = a.MenuId,
                           IsDeleted = a.IsDeleted,
                           MenuName = a.MenuName,
                           MenuOrder = a.MenuOrder,
                           PId = a.PId,
                           MenusUrl = a.MenusUrl,
                           PName = b.MenuName,
                           CreationDate = a.CreationDate,
                           Creator = a.Creator,
                           Updatedate = a.Updatedate,
                           Updateor = a.Updateor

                       };
            apiresult.code = Renum.显示成功;
            apiresult.Message = Renum.显示成功.ToString();
            apiresult.TotalCount = list2.Count();
            apiresult.PageCount = (int)Math.Ceiling(apiresult.TotalCount * 1.0 / request.PageSize);
            apiresult.Items = list2.OrderBy(x => x.MenuOrder).Skip((request.PageIndex - 1) / request.PageSize).Take(request.PageSize).ToList();
            return Task.FromResult(apiresult);
                               
                              
        }
    }
}
